package com.genius.reservation.receiveManager.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.unit.DataUnit;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpConnection;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.genius.reservation.UseTime.service.IUseTimeService;
import com.genius.reservation.car.entity.ReservationStartCarInformation;
import com.genius.reservation.common.ResponseRule;
import com.genius.reservation.mapper.ReceiveRecordInformationMapper;
import com.genius.reservation.mapper.ReservationStartCarInformationMapper;
import com.genius.reservation.order.entity.OrderInformation;
import com.genius.reservation.order.service.IOrderInformationService;
import com.genius.reservation.receiveManager.service.IReceiveManagerInformationService;
import com.genius.reservation.receiveManager.service.impl.ReceiveManagerInformationServiceImpl;
import com.genius.reservation.receiveRecord.entity.ReceiveRecordInformation;
import com.genius.reservation.reservation.entity.ReservationInformation;
import com.genius.reservation.reservation.service.IReservationInformationService;
import com.genius.reservation.tools.annotation.webLog;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 收货主管 前端控制器
 * </p>
 *
 * @author baomidou
 * @since 2022-05-26
 */
@RestController
@RequestMapping("/reservation/receiveManager")
@Api(tags = "收货主管控制器",value = "收货主管控制器")
public class ReceiveManagerInformationController {
    @Autowired
    IReceiveManagerInformationService reser;

    @Autowired
    IReservationInformationService reservationService;

    @Autowired
    @Lazy
    ReservationStartCarInformationMapper startCarMapper;

    @Autowired
    @Lazy
    ReceiveRecordInformationMapper recordMapper;

    @Autowired
    IOrderInformationService orderInformationService;


    @GetMapping("/getAllReservation")
    @ApiOperation("获取所有订单")
    JSONObject getAllReservation(@RequestParam("page") int page,@RequestParam("limit") int limit){
        return reservationService.getAllReservation(page,limit);
    }

    @PostMapping("/getMessage")
    @ApiOperation("获取某一订单")
    ResponseRule getReservation(@ApiParam("订单号") @RequestParam String reservationNumber){
        return reser.getMessage(reservationNumber);
    }

    @GetMapping("/getAllMessage")
    @ApiOperation("获取所有消息")
    ResponseRule getAllMessage(){
        return reser.getAllMessage();
    }

//    @PostMapping("/cancelReservation")
//    ResponseRule cancelReservation(@RequestParam String reservationNumber){
//        return reservationService.cancelReceiver(reservationNumber);
//    }

    //确认时间和收货员和月台号
    @PostMapping("/confirmReservation/{reservationNumber}")
    @ApiOperation("收货主管确认预约单")
    @webLog
    ResponseRule confirmReservation(@PathVariable String reservationNumber, @RequestBody JSONObject body){
        String confirmArrivalTime = body.getString("confirmArrivalTime");
        String confirmOverTime = body.getString("confirmOverTime");
        Integer trayCount = body.getInteger("trayCount");
        LambdaQueryWrapper<OrderInformation> eq = new LambdaQueryWrapper<OrderInformation>().eq(OrderInformation::getReservationNumber, reservationNumber).last("limit 1");
        OrderInformation one = orderInformationService.getOne(eq);
        String result = HttpRequest.get("http://39.107.83.199:8045/api/EditGoodsClass/ValidDate?billno=" + one.getOrderNumber()).execute().body();
        DateTime conTime = new DateTime(confirmArrivalTime);
        DateTime maxTime = new DateTime(new Integer(result)*1000L);
        long between = DateUtil.between(conTime, maxTime, DateUnit.SECOND, false);
        if(between<=0){
            return  ResponseRule.no("选择日期不能超过最大日期"+maxTime.toDateStr());
        }

        Integer driverCount = body.getInteger("driverCount");
        List<JSONObject> cars = new ArrayList<>();
        for (int i = 0; i <= driverCount-1 ; i++) {
            JSONObject car = new JSONObject();
            car.put("carId", body.getString("carId[" + (i) + "]"));
            car.put("receiver", body.getString("confirmReceiverNumber["+(i)+"]"));
            car.put("platform", body.getString("confirmPlatformNumber["+(i)+"]"));
            cars.add(car);
        }
        return reservationService.confirmReservation(reservationNumber,confirmArrivalTime,confirmOverTime,trayCount,cars);
    }

    @PostMapping("/finishReservation")
    @ApiOperation("完成预约单")
    ResponseRule finishReservation(@RequestParam String reservationNumber){
        return reservationService.finishReservationReceiver(reservationNumber);
    }

    @GetMapping("/findFreePlatform")
    @ApiOperation("寻找空闲月台")
    ResponseRule findFreePlatform(){
        return reservationService.findFreePlatform();
    }

    @GetMapping("/findFreeReceiver")
    @ApiOperation("寻找空闲收货员")
    ResponseRule findFreeReceiver(){
        return reservationService.findFreeReceiver();
    }


    @PostMapping("/changePlatform")
    @ApiOperation("更改收货月台")
    @webLog
    ResponseRule changePlatform(@RequestBody JSONObject body)
    {
        String reservationNumber = body.getString("reservationNumber");
        Integer driverCount = body.getInteger("driverCount");
        List<JSONObject> cars = new ArrayList<>();
        for (int i = 0; i <= driverCount-1; i++) {
            JSONObject car = new JSONObject();
            car.put("carId", body.getString("carId[" +i+ "]"));
            car.put("receiver", body.getString("confirmReceiverNumber["+i+"]"));
            car.put("platform", body.getString("confirmPlatformNumber["+i+"]"));
            cars.add(car);
        }
        return reser.changePlatformAndReceiver( reservationNumber, cars);
    }

    @GetMapping("/getUncompletedReservation")
    @ApiOperation("获取未完成订单")
    ResponseRule getUncompletedReservation(){
        return reser.getUncompletedReservation();
    }
    @GetMapping("/getCompleteReservation")
    @ApiOperation("获取已完成订单")
    ResponseRule getCompleteReservation(){
        return reser.getCompleteReservation();
    }
    @GetMapping("/getLateReservation")
    @ApiOperation("获取超时订单")
    ResponseRule getLateReservation(){
        return reser.getLateReservation();
    }
    @GetMapping("/getUnlateReservation")
    @ApiOperation("获取早到订单")
    ResponseRule getUnlateReservation(){
        return reser.getUnlateReservation();
    }

    @PostMapping("/getPlatform")
    @ApiOperation("根据月台编号获取月台信息")
    ResponseRule getPlatform(@RequestBody JSONObject object){
        return reser.getPlatformById(object.getString("platformNumber"));
    }

    @GetMapping("/getUnReservation")
    @ApiOperation("获取订单")
    ResponseRule getUnReservation(){
        return reser.getUncompletedReservation();
    }
    @GetMapping("/getConfirmReservation")
    @ApiOperation("获取确认订单")
    ResponseRule getConfirmReservation(){
        return reser.getConfirmReservation();
    }

    @GetMapping("/getReceivingReservation")
    @ApiOperation("获取收获中订单")
    ResponseRule getReceivingReservation(){
        return reser.getReceivingReservation();
    }

    @GetMapping("/getReceivedReservation")
    @ApiOperation("获取完成收货订单")
    ResponseRule getReceivedReservation(){
        return reser.getReceivedReservation();
    }
    @GetMapping("/getReceiveErr")
    @ApiOperation("获取收货异常")
    ResponseRule getReceiveErr(){
        return reser.getReceiveErr();
    }
    @GetMapping("/getReservationErr")
    @ApiOperation("获取预约异常")
    ResponseRule getReservationErr(){
        return reser.getReservationErr();
    }

    @PostMapping("/checkUsedTime")
    @ApiOperation("获取此时间段可以用的月台")
    ResponseRule checkUsedTime(@RequestParam String time){
        DateTime parse = DateUtil.parse(time);
        return reservationService.checkUsedTime("" + parse.year(), "" + parse.month(), "" + parse.dayOfMonth(), "" + parse.hour(true));
    }

//    @PostMapping("/getReservationCount")
//    @ApiOperation("获取货物总数")
//    ResponseRule getReservationCount(@RequestBody JSONObject body){
//        String reservationNumber = body.getString("reservationNumber");
//        LambdaQueryWrapper<ReservationStartCarInformation> eq = startCarMapper.getWrapper().eq(ReservationStartCarInformation::getReservationNumber, reservationNumber);
//        List<ReservationStartCarInformation> receiveRecordInformations = startCarMapper.selectList(eq);
//        if (ArrayUtil.isEmpty(receiveRecordInformations)) {
//            return ResponseRule.no("未找到订单信息");
//        }
//        Integer totalCount=0;
//        for (ReservationStartCarInformation receiveRecordInformation : receiveRecordInformations) {
//            totalCount += receiveRecordInformation.get
//        }
//    }

    @PostMapping("/getRecord")
    ResponseRule getRecord(@RequestParam String receiveRecordNumber){
        LambdaQueryWrapper<ReceiveRecordInformation> eq = recordMapper.getWrapper().eq(ReceiveRecordInformation::getReceiveRecordNumber, receiveRecordNumber);
        ReceiveRecordInformation receiveRecordInformation = recordMapper.selectOne(eq);
        if (ObjectUtil.isEmpty(receiveRecordInformation)) {
            return ResponseRule.no("没有找到记录");
        }
        return ResponseRule.ok(receiveRecordInformation);
    }


    @PostMapping("/checkUsedReceiver")
    ResponseRule checkUsedReceiver(@RequestParam String time){
        DateTime parse = DateUtil.parse(time);
        return reservationService.checkUsedReceiver("" + parse.year(), "" + parse.month(), "" + parse.dayOfMonth(), "" + parse.hour(true));
    }

    @PostMapping("/checkTimeIsUse")
    ResponseRule checkTimeIsUse(@RequestParam String startTime,@RequestParam String overTime,@RequestParam String platformNumber){
        return reservationService.checkTimeIsUse(startTime,overTime,platformNumber);
    }

    @PostMapping("/checkReceiverIsUse")
    ResponseRule checkReceiverIsUse(@RequestParam String startTime,@RequestParam String overTime,@RequestParam String receiverNumber){
        return reservationService.checkReceiverIsUse(startTime,overTime,receiverNumber);
    }

    @PostMapping("/freePlatformByTime")
    @ApiOperation("获取此时间段可以用的月台")
    ResponseRule freePlatformByTime(@RequestParam String startTime,@RequestParam Integer keepTime){
        return reservationService.freePlatformByTime(startTime,keepTime);
    }

    @PostMapping("/freeReceiverByTime")
    @ApiOperation("获取此时间段可以用的收货员")
    ResponseRule freeReceiverByTime(@RequestParam String startTime,@RequestParam Integer keepTime){
        return reservationService.freeReceiverByTime(startTime,keepTime);
    }



    @PostMapping("/filterTable")
    @ApiOperation("关键字搜索")
    JSONObject filterTable(@RequestParam Map<String,String> search,@RequestParam int page,@RequestParam int limit){
        return reservationService.searchTable(search.get("search[key]"),search.get("search[value]"),page,limit);
    }


    @PostMapping("/checkBoxamount")
    @ApiOperation("获取托盘数")
    ResponseRule checkBoxamount(@RequestParam Map<String,String> map) throws IOException {
        List<Map<String,String>> orders = new ArrayList<>();
        HttpResponse all = HttpRequest.post("http://39.107.83.199:8045/api/EditGoodsClass/BilOrderInfo")
                .body("{OrderNO:'"+map.get("OrderNO")+"'}")
                .header("Content-Type", "application/json;charset=UTF-8")
                .execute();
        JSONArray objects = JSONObject.parseArray(all.body());
        for (int i =0;i<=objects.size()-1;i++){
            JSONObject jsonObject = objects.getJSONObject(i);
            String gdscode = jsonObject.getString("gdscode");
            String amount = String.valueOf(NumberUtil.parseInt(jsonObject.getString("amount")));
            HashMap<String, String> js = new HashMap<>();
            js.put("GoodsNO",gdscode);
            js.put("Amount",amount);
            orders.add(js);
        }
        String s = JSONObject.toJSONString(orders);
        HttpResponse box = HttpRequest.post("http://39.107.83.199:8045/api/EditGoodsClass/Boxamount")
                .body("{Dtl:"+s+"}")
                .header("Content-Type", "application/json;charset=UTF-8")
                .execute();
        return ResponseRule.ok(box.body());
    }


    @PostMapping("/cancelReservation")
    @ApiOperation("取消订单")
    ResponseRule cancelReservation(@RequestParam String reservationNumber){
        return reservationService.cancelReceiver(reservationNumber);
    }

    @PostMapping("/getAllFreeReceiverByTime")
    @ApiOperation("获取这个时间段没事的收货员")
    ResponseRule getAllFreeReceiverByTime(@RequestParam String startTime,@RequestParam Integer keepTime){
        return reservationService.getAllFreeReceiverByTime( startTime,keepTime);
    }

    @PostMapping("/getAllFreePlatformByTime")
    @ApiOperation("获取这个时间段空闲月台")
    ResponseRule getAllFreePlatformByTime(@RequestParam String startTime,@RequestParam Integer keepTime){
        return reservationService.getAllFreePlatformByTime( startTime,keepTime);
    }
}
